package com.erp.controller;


import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.erp.Utils.DateFormat;
import com.erp.Utils.ResponseModel;
import com.erp.entity.Label;
import com.erp.enums.statusCode;
import com.erp.service.LabelService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 标签表 前端控制器
 * </p>
 *
 * @author  张彬 
 * @since 2021-10-14
 */
@RestController
@RequestMapping("/label")
public class LabelController {
    @Resource
    LabelService labelService;

    @PreAuthorize("hasAnyAuthority('label:list')")
    @RequestMapping(value = "listView",method = RequestMethod.GET)
    public ModelAndView listView(){
        ModelAndView mav = new ModelAndView();
        mav.setViewName("system/label/label_list");
        return mav;
    }

    @RequestMapping(value = "/getListData",method = RequestMethod.GET)
    @ResponseBody
    @PreAuthorize("hasAnyAuthority('label:list')")
    public Map<String,Object> getListData(@RequestParam(value = "page") int page,
                                          @RequestParam(value = "limit") int limit,
                                          @RequestParam(value = "labelName",required = false) String labelName,
                                          @RequestParam(value = "start",required = false) String start,
                                          @RequestParam(value = "end",required = false) String end){
        QueryWrapper<Label> wrapper = new QueryWrapper<>();
        if (StrUtil.isNotEmpty(labelName)){
            wrapper.like("label_name",labelName);
        }
        if (StrUtil.isNotEmpty(start) && StrUtil.isNotEmpty(end)){
            // 时间偏于一天
            Date date = DateUtil.parse(end,"yyyy-MM-dd");
            Date newDate = DateUtil.offset(date, DateField.DAY_OF_MONTH, 1);
            String formatDate = DateUtil.formatDate(newDate);
            wrapper.ge("create_time",start).le("create_time",formatDate);
        }
        wrapper.eq("status",statusCode.Default.getValue()).orderByDesc("create_time");
        IPage<Label> userPage = new Page<>(page, limit);//参数一是当前页，参数二是每页个数
        if ((StrUtil.isNotEmpty(start) && StrUtil.isNotEmpty(end)) || StrUtil.isNotEmpty(labelName)){
            userPage = labelService.page(userPage, wrapper);
        }else{
            userPage = labelService.page(userPage, wrapper);
        }
        List<Label> labelList = userPage.getRecords();//获取数据，这里面还有当前页码数还有总数据参数
        Map<String,Object> map = new HashMap<>();
        map.put("code",0);
        map.put("msg","");
        map.put("count",userPage.getTotal());
        map.put("data",labelList);
        return map;
    }

    @RequestMapping(value = "addView",method = RequestMethod.GET)
    @PreAuthorize("hasAnyAuthority('label:add')")
    public ModelAndView addView(){
        ModelAndView mav = new ModelAndView();
        mav.setViewName("system/label/addView");
        return mav;
    }

    @RequestMapping(value = "/add",method = RequestMethod.POST)
    @ResponseBody
    @PreAuthorize("hasAnyAuthority('label:add')")
    public ResponseModel add(@RequestBody JSONObject data){
        String labelName = (String) data.get("labelName");
        String labelInfo = (String) data.get("labelInfo");
        Label label = new Label();
        label.setLabelName(labelName);
        label.setLabelInfo(labelInfo);
        label.setCreateTime(DateFormat.getTime());
        label.setStatus(statusCode.Default.getValue());
        labelService.save(label);
        return ResponseModel.success();
    }

    @RequestMapping(value = "editView",method = RequestMethod.GET)
    @PreAuthorize("hasAnyAuthority('label:edit')")
    public ModelAndView editView(@RequestParam int id){
        Label label = labelService.getById(id);
        ModelAndView mav = new ModelAndView();
        mav.addObject("label",label);
        mav.setViewName("system/label/editView");
        return mav;
    }

    @ResponseBody
    @RequestMapping(value = "/edit",method = RequestMethod.POST)
    @PreAuthorize("hasAnyAuthority('label:edit')")
    public ResponseModel edit(@RequestBody JSONObject data){
        String labelName = data.getStr("labelName");
        String labelInfo = data.getStr("labelInfo");
        Label label = new Label();
        label.setId(Convert.toInt(data.get("labelId")));
        label.setLabelName(labelName);
        if (StrUtil.isNotEmpty(labelInfo)){
            label.setLabelInfo(labelInfo);
        }
        boolean status = labelService.updateById(label);
        if (status){
            return ResponseModel.success("修改成功");
        }else{
            return ResponseModel.fail("修改失败");
        }
    }

    //删除
    @RequestMapping(value = "/delete",method = RequestMethod.POST)
    @ResponseBody
    @PreAuthorize("hasAnyAuthority('label:del')")
    public ResponseModel del(@RequestBody Label label){
//        boolean status = labelService.removeById((int)data.get("labelId"));
        label.setStatus(statusCode.Delete.getValue());
        //做逻辑删除
        boolean status = labelService.updateById(label);
        if (status){
            return ResponseModel.success("删除成功");
        }else{
            return ResponseModel.fail("删除失败");
        }
    }
    // 批量删除
    @RequestMapping(value = "/batch/delete",method = RequestMethod.POST)
    @ResponseBody
    @PreAuthorize("hasAnyAuthority('label:del')")
    public ResponseModel batchDel(@RequestBody  List<Label> labelList){
//        boolean status = labelService.removeByIds(idList);
        for (Label label:labelList){
            label.setStatus(statusCode.Delete.getValue());
        }
        boolean status = labelService.updateBatchById(labelList);
        if (status){
            return ResponseModel.success("删除成功");
        }else{
            return ResponseModel.fail("删除失败");
        }
    }
}
